package cn.gson.fengboot.controller;

import cn.gson.fengboot.model.pojos.QempFrom;
import cn.gson.fengboot.model.service.DempService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.UUID;

@Controller
public class DimageController {

    @Autowired
    DempService dempService;

    /*头像上传*/
    String url ="D:/personageimage";

    @PostMapping("/personageimage")
    @ResponseBody
    public String upload(@RequestParam("file")
                         MultipartFile file, HttpSession session){
        try {
            String uuidname = UUID.randomUUID().toString();//生成全球唯一码
            String filepath = uuidname + ".png";//生成图片路径
            File f = new File(url,filepath);
            if(!f.exists()){
                f.mkdirs();//如果目录不存在，创建
            }
            file.transferTo(f);//文件转移
            QempFrom user = (QempFrom)session.getAttribute("user");//获取session用户
            String path = "http://localhost:8088/personageimage/"+filepath;//数据库图片路径
            dempService.personageimage(user.getEmpId(),path);//保存头像
            return path;//回显路径
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("personageimage/**")
    @ResponseBody
    public void upload(HttpServletRequest request, HttpServletResponse response){
        String servletPath = request.getServletPath();
        String path = url +"/"+ servletPath.replaceFirst("/personageimage/","");
        System.out.println("我是路径"+path);
        File file = new File(path);
        if(!file.exists()){
            try {
                response.sendError(404,"路径不存在");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            //使用字节流把图片从把本地读取到内存里
            InputStream is = new FileInputStream(file);
            //servlet中的流将图片传回客户端
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            //循环读取
            while ((len = is.read(b))!=-1){
                outputStream.write(b,0,len);
            }
            outputStream.close();//先关输出流
            is.close();//在关输入流


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
